<template>
  <view class="content">
    <doctor
      v-if="role == 4"
      ref="doctor"
      @showActionSheet="showActionSheet"
      :roleName="showRole ? roleObj[role].name : ''"
    />
    <patient
      v-if="role == 5"
      ref="patient"
      @showActionSheet="showActionSheet"
      :roleName="showRole ? roleObj[role].name : ''"
    />
  </view>
</template>

<script>
import patient from "./components/patient/index.vue";
import doctor from "./components/doctor/index.vue";
import qs from "query-string";
export default {
  components: { patient, doctor },
  data() {
    return {
      token: uni.getStorageSync("token"),
      role: "",
      roleObj: {
        2: { name: "平台管理员", title: "平台管理员" },
        3: { name: "医院领导", title: "医院领导" },
        4: { name: "医生", title: "医生工作台" },
        5: { name: "患者", title: "患者中心" },
      },
      showRole: true,
      must: false,
      time: 0,
    };
  },
  onShareAppMessage() {
    return this.$util.returnShareObj();
  },
  onLoad(options) {
	uni.removeStorageSync('doctorId')
	if(options){
		let qrCode=options.scene || options.q
		if(qrCode){
			let urlObj = qs.parse(decodeURIComponent(qrCode).split("?")[1]);
			if(urlObj.doctorId){
				uni.setStorageSync('doctorId',urlObj.doctorId)
			}
		}
	}
    if (this.token) {
      this.getRole();
    } else {
      let wx = false;
      //#ifdef MP-WEIXIN
      if (uni.getAccountInfoSync().miniProgram.envVersion == "release") {
        wx = true;
      }
      //#endif
      if (wx) {
        this.login();
      } else {
        this.phoneLogin();
      }
    }
  },
  onShow() {
    if (this.must) {
      this.$util.goUrl("/pages/selectRole/index");
    }
    if (this.role) {
      uni.setNavigationBarTitle({ title: this.roleObj[this.role].title });
      if (this.role == 4) {
        this.$refs.doctor.init();
      } else if (this.role == 5) {
        this.$refs.patient.init();
      }
    }
  },
  methods: {
    //验证码登录
    phoneLogin() {
      this.$api
        .login({
          phone: "552d7a5bccf7a4",
          smsCode: "MjM0MnNh",
        })
        .then((res) => {
          if (res.code == 200) {
            uni.setStorage({
              key: "token",
              data: res.data.token,
              success: () => {
                this.getRole();
              },
            });
          }
        });
    },
    //登录
    login() {
      uni.login({
        success: (loginRes) => {
          this.$api
            .loginByWxOuth({
              code: loginRes.code,
            })
            .then((res) => {
              if (res.code == 200) {
                if (res.data.token) {
                  uni.setStorage({
                    key: "token",
                    data: res.data.token,
                    success: () => {
                      this.getRole();
                    },
                  });
                } else {
                  uni.reLaunch({
                    url: "/pages/login/index?openid=" + res.data.openid,
                  });
                }
              } else {
                uni.showModal({
                  title: "提示",
                  content: "登陆失败，点击确定以重试",
                  showCancel: false,
                  success: (res1) => {
                    if (res1.confirm) {
                      this.login();
                    }
                  },
                });
              }
            });
        },
      });
    },
    //获取角色
    getRole() {
      this.$api.getUserRoles().then((res) => {
        if (res.code == 200) {
          let role = uni.getStorageSync("role");
          if (res.data.indexOf(",") < 0) {
            this.refreshByBack(res.data);
            uni.removeStorageSync("roleIds");
          } else {
            uni.setStorage({
              key: "roleIds",
              data: res.data,
              success: () => {
                if (role && res.data.indexOf(role) > -1) {
                  this.role = role;
                  this.init();
                } else {
                  //前往选择身份,且必须选择
                  this.must = true;
                  this.$util.goUrl("/pages/selectRole/index");
                }
              },
            });
          }
        }
      });
    },
    //选择身份回调
    refreshByBack(data) {
      if (data == "refreshDoctorData") {
        this.$refs.doctor.init();
      } else {
        this.must = false;
        this.role = data;
        this.init();
        uni.setStorage({
          key: "role",
          data: this.role,
        });
      }
    },
    //初始化数据
    init() {
      uni.setNavigationBarTitle({ title: this.roleObj[this.role].title });
      this.$nextTick(() => {
        if (this.role == 4) {
          this.$refs.doctor.init();
        } else if (this.role == 5) {
          this.$refs.patient.init();
        }
      });
    },
    showActionSheet(avatar) {
      if (avatar) {
        uni.showActionSheet({
          itemList: ["预览", "更换"],
          success: (res) => {
            if (res.tapIndex == 0) {
              uni.previewImage({
                current: 0,
                urls: [avatar],
              });
            } else {
              this.uploadPicture();
            }
          },
        });
      } else {
        this.uploadPicture();
      }
    },
    uploadPicture() {
      uni.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
          if (res.tempFilePaths) {
            this.$util.uploadPicture(res.tempFilePaths[0], "头像", (res) => {
              let data = {
                avatar: res.data,
              };
              if (this.role == 4) {
                data.doctorId = uni.getStorageSync("doctorId");
              } else if (this.role == 5) {
                data.patientId = uni.getStorageSync("patientId");
              }
              this.$api[this.role == 4 ? "doctorUpdateDoctor" : "patientUpdatePatient"](data).then((res1) => {
                if (res1.code == 200) {
                  if (this.role == 4) {
                    this.$refs.doctor.setAvatar(res.data);
                  } else if (this.role == 5) {
                    this.$refs.patient.setAvatar(res.data);
                  }
                  this.$util.showSuccessToast("头像上传成功");
                }
              });
            });
          }
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.content {
  background: $back-grey-color;
  height:100vh;
  overflow-y: hidden;
}
</style>
